# file_utils.py

import os
import hashlib
import shutil

def list_files(directory):
    return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

#创建目录
def create_folder(folder_path):
    try:
        os.makedirs(folder_path)
        print(f"文件夹 '{folder_path}' 创建成功！")
    except FileExistsError:
        print(f"文件夹 '{folder_path}' 已经存在。")

def calculate_md5(file_path):
    md5_hash = hashlib.md5()
    with open(file_path, "rb") as f:
        # 分块读取文件，适用于大文件
        for byte_block in iter(lambda: f.read(4096), b""):
            md5_hash.update(byte_block)
    return md5_hash.hexdigest()

#删除零时目录
def delete_temp_directories(root_directory):
    for root, dirs, files in os.walk(root_directory):
        for dir_name in dirs:
            if dir_name == "temp":
                temp_directory = os.path.join(root, dir_name)
                try:
                    shutil.rmtree(temp_directory)
                    print(f"Deleted: {temp_directory}")
                except Exception as e:
                    print(f"Error deleting {temp_directory}: {e}")

#读取pdf 获取页数
def get_pdf_page_count(pdf_path):
    try:
        pdf_document = fitz.open(pdf_path)
        page_count = pdf_document.page_count
        pdf_document.close()
        return page_count
    except Exception as e:
        print(f"Error: {e}")
        return None

if __name__ == "__main__":
    # 指定根目录
    folder_path = r"F:\home\catalog\uploadPath\upload\勇罕 2022年 第 4 期"
    file_names = list_files(folder_path)
    for i,file_name in enumerate(file_names, start=1):
        filename = f"{folder_path}\{file_name}"
        # new_file_name = filename.replace("勇罕 2022年 第 4 期_", f"")
        new_file_name = filename.replace(file_name, f"page{file_name}")
        os.rename(filename, new_file_name)
        print(filename+"      ===========       "+new_file_name)